import win32gui
from PyQt5.QtCore import *
import pythoncom
import PyHook3
import time
import pygetwindow


"""
这个线程注册了鼠标的点击事件，检测鼠标是否双击了预警列表，然后把点击事件传给主线程
"""


class ListenWorker(QThread):
    sinOut = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        #设置工作状态与初始num数值
        self.working = False
        self.init_mouse_value()
        self.hook()

    def __del__(self):
        #线程状态改变与线程终止
        self.working = False
        self.wait()
        pythoncom.PostQuitMessage()

    def mystart(self):
        print('**ListenWorker** coming into mystart')
        self.working = True
        if self.get_warning_win_hWnd():
            self.start()
        # pythoncom.PumpMessages()
        print('**ListenWorker** coming into mystart')

    def get_warning_win_hWnd(self):
        wins = pygetwindow.getWindowsWithTitle('预警 - (运行)')
        print('get 预警', wins)

        if len(wins) != 1:
            return False
        else:
            win = wins[0]
            warning_win = win32gui.FindWindowEx(win._hWnd, None, 'SysListView32', u'List2')
            self.win = warning_win
            return True

    def mystop(self):
        self.working = False
        # pythoncom.PostQuitMessage()

    def init_mouse_value(self):
        self.last_time = 0
        self.last_x, self.last_y = 0, 0

    def onMouse_leftdown(self, event):
        if not self.working:
            return True
        self.now_time = time.time()
        self.now_x, self.now_y = event.Position
        # TODO:这里要加上检查双击的位置
        if self.is_double_warning():
            msg = '老铁双击！' + 'X: {} Y: {}'.format(*event.Position) + 'time:{}'.format(event.Time)
            print(msg)
            # print('老铁双击！', 'X: {} Y: {}'.format(*event.Position), 'hWdn:', event.Window, 'title:', event.WindowName)
            self.sinOut.emit('check_title')
            return True
        else:
            self.last_time = self.now_time
            self.last_x, self.last_y = self.now_x, self.now_y
            return True
        # 返回 True 表示响应此事件，False表示拦截

    def is_double_warning(self):
        if self.now_time - self.last_time < 0.6 and abs(self.now_x - self.last_x) < 5 and abs(self.now_y - self.now_y) < 5:
            x1, y1, x2, y2 = win32gui.GetWindowRect(self.win)
            if x1 < self.now_x < x2 and y1 < self.now_y < y2:
                return True
        return False

    def hook(self):
        hm = PyHook3.HookManager()
        hm.MouseLeftDown = self.onMouse_leftdown
        hm.HookMouse()
        print('**ListenWorker** has start')

    def run(self):
        pythoncom.PumpMessages()
        # print('**ListenWorker** has start')
        # hm = PyHook3.HookManager()
        #
        # hm.MouseLeftDown = self.onMouse_leftdown
        # hm.HookMouse()
        # print('**ListenWorker** has start')
        # 进入循环，如不手动关闭，程序将一直处于监听状态